<template>
  <div class="login-container">
    <el-card class="login-form">
      <template #header>
        <h2>管理员登录</h2>
      </template>
      <el-form ref="loginForm" :model="user" label-width="80px">
        <el-form-item label="用户名">
          <el-input
            v-model="user.username"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input
            type="password"
            v-model="user.password"
            placeholder="请输入密码"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            style="width: 100%"
            :loading="loading"
            @click="login"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>
      <div v-if="error" class="error-message">{{ error }}</div>
      <div class="register-link">
        还没有账号？
        <router-link to="/register">注册</router-link>
      </div>
    </el-card>
  </div>
</template>

<script>
import axios from "axios";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";

export default {
  data() {
    return {
      user: {
        username: "",
        password: "",
      },
      error: "",
      loading: false,
    };
  },
  setup() {
    const router = useRouter();
    return {
      router,
    };
  },
  methods: {
    async login() {
      this.error = "";
      this.loading = true;

      try {
        const response = await axios.post(
          "http://localhost:8088/api/auth/login",
          this.user
        );
        const data = response.data;

        if (data) {
          this.router.push("/ManagerDashboard");
        }
      } catch (err) {
        if (err.response && err.response.data) {
          this.error = err.response.data;
          ElMessage.error(this.error);
        } else {
          this.error = "登录失败，请检查您的网络连接。";
          ElMessage.error(this.error);
        }
        console.error(err);
      } finally {
        this.loading = false;
      }
    },
  },
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f5f5;
}

.login-form {
  width: 400px;
}

.error-message {
  color: #f56c6c;
  margin-top: 10px;
}

.register-link {
  margin-top: 20px;
  text-align: center;
}
</style>
